package com.zcc.config;

import com.zcc.pojo.User;
import com.zcc.service.UserService;
import com.zcc.service.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //通过SecurityUtils得到subject，从中获取user对象
        User currentUser = (User)SecurityUtils.getSubject().getPrincipal();
        //给这个用户赋予权限，从用户的信息中获取
        info.addStringPermission(currentUser.getPerms());
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证");
        //从数据库中获取用户名，密码
        //获取前端传过来的令牌Token，储存了前端输入的用户名，密码
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        User user = userService.getUserByName(userToken.getUsername());

        //如果数据库和前端传来的令牌不匹配，return null，且自动抛出异常，也就是用户名或者密码错误的异常
        //验证用户名
        if (user == null) {
            return null;
        }
        //shiro验证密码，这样可以防止密码泄露
        //把用户信息传递给授权，也就是第一个参数
        return new SimpleAuthenticationInfo(user, user.getPwd(),"");
    }
}
